/**
 * 应用程序主文件
 */

class ChatApp {
  constructor() {
    this.wsClient = new WebSocketClient();
    this.ui = new UI();
    this.currentUser = null;
    
    this.init();
  }
  
  init() {
    this.bindEvents();
    this.connect();
  }
  
  bindEvents() {
    // WebSocket 事件
    this.wsClient.addEventListener('connected', () => {
      this.ui.updateConnectionStatus('connected');
      this.ui.showApp();
      this.ui.showJoinModal();
    });
    
    this.wsClient.addEventListener('disconnected', () => {
      this.ui.updateConnectionStatus('disconnected');
      this.ui.clearCurrentUser();
    });
    
    this.wsClient.addEventListener('message', (e) => {
      this.handleMessage(e.detail);
    });
    
    // UI 事件
    document.addEventListener('joinChat', (e) => {
      this.joinChat(e.detail.nickname);
    });
    
    document.addEventListener('sendMessage', (e) => {
      this.sendMessage(e.detail.message);
    });
  }
  
  connect() {
    this.ui.updateConnectionStatus('connecting');
    this.wsClient.connect();
  }
  
  joinChat(nickname) {
    const userId = Utils.generateId();
    this.currentUser = { userId, nickname };
    
    this.wsClient.send('join', { userId, nickname });
    this.ui.hideModal('userModal');
    this.ui.setCurrentUser(this.currentUser);
  }
  
  sendMessage(content) {
    if (!this.currentUser) return;
    
    this.wsClient.send('message', content);
  }
  
  handleMessage(message) {
    switch (message.type) {
      case 'join':
        if (message.content.onlineUsers) {
          this.ui.updateOnlineUsers(message.content.onlineUsers);
        }
        if (message.content.messageHistory) {
          message.content.messageHistory.forEach(msg => {
            this.ui.addMessage(msg);
          });
        }
        break;
        
      case 'message':
      case 'broadcast':
        this.ui.addMessage(message);
        if (message.from !== this.currentUser?.userId) {
          this.ui.showNotification('新消息', 'message');
        }
        break;
        
      case 'error':
        this.ui.showNotification(message.content.message, 'error');
        break;
    }
  }
}

// 启动应用
document.addEventListener('DOMContentLoaded', () => {
  window.chatApp = new ChatApp();
});